package launcher;

import java.util.HashMap;
import java.util.Map;

import strings.Messages;
import ui.Display;

import common.Connection;

public abstract class Script extends Thread {

	protected Display display;
	protected Connection conn;

	private Map<String, Object> data;

	public Script(String name, Display display, Connection conn) {
		super(name);
		this.display = display;
		this.conn = conn;
		data = new HashMap<String, Object>();
	}

	public void run() {
		if (display != null) {
			display.setTitle(getName());
			display.setVisible(true);
		}
		
		if (conn != null)
			conn.initSession();

		exec();

		if (conn != null)
			conn.closeSession();
	}

	public abstract void exec();

	@SuppressWarnings("rawtypes")
	protected Object getParameter(String key, final Class dataType, boolean nullAllowed) {
		if (key == null || dataType == null) {
			System.out.printf(Messages.getString("Script.0"), key, dataType); //$NON-NLS-1$
			System.exit(-1);
		}

		Object value = data.get(key);
		if (value == null && !nullAllowed) {
			System.out.printf(Messages.getString("Script.1"), key, dataType, value); //$NON-NLS-1$
			System.exit(-1);
		}

		if (value == null && nullAllowed)
			return null;

		if (!dataType.isInstance(value)) {
			System.out.printf(Messages.getString("Script.2"), key, dataType, value); //$NON-NLS-1$
			System.exit(-1);
		}

		return value;
	}

	@SuppressWarnings("rawtypes")
	protected Object getParameter(String key, final Class dataType) {
		return getParameter(key, dataType, false);
	}

	public void setParameter(String key, Object value) {
		if (key != null)
			data.put(key, value);
	}
}
